package com.project.controller;

import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;

import com.project.common.Constants;
import com.project.entity.BaseEntity;
import com.project.service.BaseService;

public abstract class BaseController<T extends BaseEntity> {
	
	@Autowired
	public BaseService<T> service;
	
	protected abstract Class<T> getClazz();
	
	private static final String[] color = new String[]{"primary","info","success","warning","danger","inverse","pink","purple","yellow","grey","light"};
	
	private T entity;

	public T getEntity() {
		return entity;
	}

	public void setEntity(T entity) {
		this.entity = entity;
	}



	/**
	 * 所有RequestMapping调用钱的model绑定方法，
	 * 先根据form的id从数据查询出对象，再把form
	 * 提交的内容绑定到该对象上。只有在接受到id参数
	 * 该方法才被调用
	 */
	@ModelAttribute
	public void prepare(@RequestParam(required=false,value="id") Long id,Model model){
		if(id != null){
			entity = service.getById(getClazz(),id);
		}else{
			try {
				entity =   getClazz().newInstance();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		model.addAttribute("entity", entity);
		model.addAttribute("ossUrl", Constants.OBJECT_STORAGE_URL_DOWNLOAD_IMAGE);
	}
	
	@InitBinder  
	public void initBinder(WebDataBinder binder) {
			binder.registerCustomEditor(Date.class, new SysCustomDateEditor()); 
//		    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//		    SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
//		    dateFormat.setLenient(false);  
//		    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
//	        binder.registerCustomEditor(Timestamp.class, new CustomDateEditor(datetimeFormat, true)); 
//	        binder.registerCustomEditor(Time.class, new CustomDateEditor(timeFormat, true)); 
	}
}


